<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      :model="formData"
      ref="formRef"
      :rules="formRules"
      vloading="formLoading"
      label-width="auto"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="护理计划名称" prop="planName">
            <el-input
              v-model="formData.planName"
              placeholder="请输入护理计划名称"
              :clearable="true"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="简介" prop="planIntroduction">
            <el-input
              v-model="formData.planIntroduction"
              placeholder="请输入简介"
              :clearable="true"
              type="textarea"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-form-item>
      <el-button @click="clickAddItem">添加护理项目</el-button>
      <el-button @click="clickDeleteItem">删除护理项目</el-button>
    </el-form-item>
    <Table
      :columns="columns"
      :adaptive="true"
      :data="formData.details"
      save-key="NursePlanEdit"
      :row-style="rowStyle"
      @row-click="handleRowClick"
    >
      <template #execType="{ row }">
        <el-select v-model="row.execType" @change="handleChangeExecType(row)">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.NURSE_PLAN_EXEC_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </template>
      <template #execFrequency="{ row }">
        <el-select
          v-model="row.execFrequency"
          v-if="row.execType == NursePlanExecTypeEnum.MOUTH"
          multiple
        >
          <el-option
            v-for="date in dateList"
            :key="date.value"
            :label="date.label"
            :value="date.value"
          />
        </el-select>
        <el-select
          v-model="row.execFrequency"
          v-else-if="row.execType == NursePlanExecTypeEnum.WEEK"
          multiple
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_WEEK)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
        <InputNumber
          class="!w-70px"
          v-model="row.execFrequency[0]"
          v-else-if="row.execType == NursePlanExecTypeEnum.XDAY"
        />
        <div v-else></div>
      </template>
      <template #execTime="{ row }">
        <el-select v-model="row.execTime" multiple>
          <el-option v-for="time in execTimeList" :key="time" :label="time" :value="time" />
        </el-select>
      </template>
    </Table>
    <template #footer>
      <el-button type="primary" :disabled="formLoading" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <NurseItemSelect ref="itemSelectRef" @select-value="handleSelectItem" />
</template>
<script setup name="NursePlanEdit" lang="ts">
import * as NursePlanApi from '@/api/nurse/nursePlan'
import NurseItemSelect from '../nurseItem/NurseItemSelect.vue'
import * as NursePlanModel from '@/model/nurse/plan/NursePlan'
import * as NursePlanDetailModel from '@/model/nurse/plan/NursePlanDetail'
import { NursePlanExecTypeEnum } from '@/utils/constants'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import InputNumber from '@/components/InputNumber/src/InputNumber.vue'
interface NursePlanDetailEdit extends NursePlanDetailModel.NursePlanDetail {
  item: {
    itemName: string
  }
  operateType: string
}
interface NursePlanEdit extends NursePlanModel.NursePlan {
  details: NursePlanDetailEdit[]
}
const { t } = useI18n()
const message = useMessage()
const itemSelectRef = ref()
let formType = ''
const dialogTitle = ref('')
const dialogVisible = ref(false)
const formRef = ref()
const formLoading = ref(false)
const formData = ref<NursePlanEdit>({
  id: undefined,
  planName: '',
  planIntroduction: '',
  details: []
})
const formRules = reactive({
  planName: [{ required: true, message: '请输入护理计划名称', trigger: 'blur' }]
})
const tableCurrentRow = ref()
const columns = [
  {
    label: '护理名称',
    prop: 'item.itemName'
  },
  {
    label: '执行方式',
    prop: 'execType',
    slot: 'execType'
  },
  {
    label: '执行频率',
    prop: 'execFrequency',
    slot: 'execFrequency'
  },
  {
    label: '执行时间',
    prop: 'execTime',
    slot: 'execTime'
  }
]
const dateList = [
  { label: '1号', value: 1 },
  { label: '2号', value: 2 },
  { label: '3号', value: 3 },
  { label: '4号', value: 4 },
  { label: '5号', value: 5 },
  { label: '6号', value: 6 },
  { label: '7号', value: 7 },
  { label: '8号', value: 8 },
  { label: '9号', value: 9 },
  { label: '10号', value: 10 },
  { label: '11号', value: 11 },
  { label: '12号', value: 12 },
  { label: '13号', value: 13 },
  { label: '14号', value: 14 },
  { label: '15号', value: 15 },
  { label: '16号', value: 16 },
  { label: '17号', value: 17 },
  { label: '18号', value: 18 },
  { label: '19号', value: 19 },
  { label: '20号', value: 20 },
  { label: '21号', value: 21 },
  { label: '22号', value: 22 },
  { label: '23号', value: 23 },
  { label: '24号', value: 24 },
  { label: '25号', value: 25 },
  { label: '26号', value: 26 },
  { label: '27号', value: 27 },
  { label: '28号', value: 28 },
  { label: '29号', value: 29 },
  { label: '30号', value: 30 },
  { label: '31号', value: 31 }
]
const execTimeList = [
  '00:00',
  '00:30',
  '01:30',
  '02:00',
  '02:30',
  '03:00',
  '03:30',
  '04:00',
  '04:30',
  '05:00',
  '05:30',
  '06:00',
  '06:30',
  '07:00',
  '07:30',
  '08:00',
  '08:30',
  '09:00',
  '09:30',
  '10:00',
  '10:30',
  '11:00',
  '11:30',
  '12:00',
  '12:30',
  '13:00',
  '13:30',
  '14:00',
  '14:30',
  '15:00',
  '16:00',
  '16:30',
  '17:00',
  '17:30',
  '18:00',
  '18:30',
  '19:00',
  '19:30',
  '20:00',
  '20:30',
  '21:00',
  '21:30',
  '22:00',
  '22:30',
  '23:00',
  '23:30'
]
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await NursePlanApi.get(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    planName: '',
    planIntroduction: '',
    details: []
  }
  formRef.value?.resetFields()
}

const emit = defineEmits(['success'])
/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as NursePlanEdit
    if (formType === 'create') {
      await NursePlanApi.create(data)
      message.success(t('common.createSuccess'))
    } else {
      await NursePlanApi.update(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** table行的style的回调方法 */
const rowStyle = ({ row }) => {
  if (row?.operateType == 'delete') {
    return { display: 'none' }
  } else return {}
}

/** table行点击事件 */
const handleRowClick = (row) => {
  tableCurrentRow.value = row
}
const handleSelectItem = (selectItemList) => {
  selectItemList.forEach((element) => {
    const existDetails = formData.value.details.filter((detail) => detail.itemId == element.id)
    if (existDetails.length > 0) {
      existDetails.forEach((detail) => {
        if (formType !== 'create') {
          if (detail.id != undefined) detail.operateType = 'update'
          else detail.operateType = 'new'
        }
      })
      return
    }

    const detail = {
      id: undefined,
      planId: formType === 'create' ? undefined : formData.value.id,
      itemId: element.id,
      execType: 1,
      execFrequency: [],
      execTime: [],
      item: {
        itemName: element.itemName
      },
      operateType: 'new'
    }
    formData.value.details.push(detail)
  })
}

const clickAddItem = () => {
  itemSelectRef.value.open()
}

const clickDeleteItem = () => {
  if (formType === 'create' || tableCurrentRow.value.id == '') {
    const index = formData.value.details.indexOf(tableCurrentRow.value)
    formData.value.details.splice(index, 1)
  } else {
    tableCurrentRow.value.operateType = 'delete'
  }
}

const handleChangeExecType = (row) => {
  if (row.execType == NursePlanExecTypeEnum.XDAY) row.execFrequency = [0]
  else row.execFrequency = []
}
</script>
